package com.halflife.comeElectricity.member.rider;

import com.halflife.comeElectricity.admin.NavStatic;
import com.halflife.comeElectricity.basic.datadic.Charge;
import com.halflife.comeElectricity.basic.datadic.ChargeRepository;
import com.halflife.comeElectricity.basic.datadic.Deposit;
import com.halflife.comeElectricity.basic.datadic.DepositRepository;
import com.halflife.framework.converter.MapHandler;
import com.halflife.framework.domain.ErrorCode;
import com.halflife.framework.domain.Page;
import com.halflife.framework.excel.ExcelRow;
import com.halflife.framework.excel.ExcelSheet;
import com.halflife.framework.participant.user.UserView;
import com.halflife.pay.wxpay.WXPayAgent;
import com.halflife.shiro.utils.ShiroUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/admin")
public class PayLogAdminController {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private PayLogRepository payLogRepository;

    @RequestMapping("/payLog/list")
    public String gotoList(@RequestParam(required = false) HashMap<String,Object> queryParam, Page page, HttpServletResponse response,
                           HttpServletRequest request, Model model)throws Exception {
        MapHandler.handleMap(queryParam);
        if (page == null) {
            page = new Page();
        }
        page.setQueryParam(queryParam);
        UserView user = ShiroUtil.getUserView(request);

        StringBuilder endSql = new StringBuilder();
        endSql.append("rider.departmentId="+user.getDepartmentId());
        endSql.append(" and t.catagory in ('押金','充值','充值其它')");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (queryParam.containsKey("beginTime")) {
            String beginDate = (String) queryParam.get("beginTime");
            Date date = sdf.parse(beginDate);
            endSql.append(" and t.createDate>=").append(date.getTime()).append("");
        }if (queryParam.containsKey("endTime")) {
            String endDate = (String) queryParam.get("endTime");
            Date date = sdf.parse(endDate);
            endSql.append(" and t.createDate<='").append(date.getTime()).append("'");
        }
        queryParam.put("endSql", endSql.toString());
        queryParam.put("status", 1);
        int totalCount = payLogRepository.selectCount(queryParam);
        List<PayLog> list = payLogRepository.selectListByPage(queryParam);
        page.setTotalCount(totalCount);
        page.setMode(model);
        model.addAttribute("list",list);
        model.addAttribute("queryParam",queryParam);
        return "payLog/list";
    }
    @RequestMapping("/payLog/list_excel")
    public void payLogToExcel(@RequestParam(required = false) HashMap<String,Object> queryParam, Page page, HttpServletResponse response,
                              HttpServletRequest request, Model model)throws Exception {
        //推送分页Map参数
        MapHandler.handleMap(queryParam);

        page.setQueryParam(queryParam);
        UserView user = ShiroUtil.getUserView(request);

        StringBuilder endSql = new StringBuilder();
        endSql.append("rider.departmentId="+user.getDepartmentId());
        endSql.append(" and t.catagory in ('押金','充值','充值其它')");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (queryParam.containsKey("beginTime")) {
            String beginDate = (String) queryParam.get("beginTime");
            Date date = sdf.parse(beginDate);
            endSql.append(" and t.createDate>=").append(date.getTime()).append("");
        }if (queryParam.containsKey("endTime")) {
            String endDate = (String) queryParam.get("endTime");
            Date date = sdf.parse(endDate);
            endSql.append(" and t.createDate<='").append(date.getTime()).append("'");
        }
        queryParam.put("endSql", endSql.toString());
        queryParam.put("status", 1);
        //查询列表
        List<PayLog> list = payLogRepository.selectAll(queryParam);
        Workbook wb = new XSSFWorkbook();
        ExcelSheet sheet = new ExcelSheet(wb);
        ExcelRow row = sheet.createRow();

        row.createCell("手机号码");
        row.createCell("骑手名称");
        row.createCell("充值金额");
        row.createCell("充值日期");
        row.createCell("开始日期");
        row.createCell("过期日期");
        row.createCell("备注");
        row.createCell("状态");
        row.createCell("月份");
        row.createCell("套餐ID");
        row.createCell("套餐名称");
        row.createCell("充值类型");
        row.createCell("优惠劵金额");
        row.createCell("退款金额");
        list.forEach((PayLog payLog)->{
            ExcelRow row_ = sheet.createRow();
            row_.createCell(payLog.getPhone());
            row_.createCell(payLog.getRiderName());
            row_.createCell(NavStatic.getBigDecimal(payLog.getPayMoney()));
            row_.createCell(NavStatic.getDate(payLog.getCreateDate()));
            row_.createCell(NavStatic.getDate(payLog.getBeginDate()));
            row_.createCell(NavStatic.getDate(payLog.getEndDate()));
            row_.createCell(payLog.getMemo());
            row_.createCell(NavStatic.getInteger(payLog.getStatus()));
            row_.createCell(NavStatic.getInteger(payLog.getMonths()));
            row_.createCell(NavStatic.getInteger(payLog.getPackageId()));
            row_.createCell(payLog.getPackageName());
            row_.createCell(payLog.getCatagory());
            row_.createCell(NavStatic.getBigDecimal(payLog.getDiscountMoney()));
            row_.createCell(NavStatic.getBigDecimal(payLog.getRefundMoney()));

        });
        response.setHeader("Content-Disposition", "attachment;filename=" + new String("充值记录.xlsx".getBytes(), "iso-8859-1"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        OutputStream os = response.getOutputStream();
        wb.write(os);
        os.close();

    }

    @Resource
    public RiderRepository riderRepository;
    @Resource
    public ChargeRepository chargeRepository;
    @Resource
    public DepositRepository depositRepository;
    @Resource
    public DiscountLogRepository discountLogRepository;
    @RequestMapping("/payLog/operate_yj")
    public String gotoOperateYj(Integer id,HttpServletResponse response,
                               HttpServletRequest request, Model model) {
        Rider rider = riderRepository.selectByPrimaryKey(id);
        if (rider.getRentType() == null) {
            throw new RuntimeException("此用户还没有租用类型");
        }
        Map map = new HashMap();
        map.put("departmentId", rider.getDepartmentId());
        map.put("valid", true);
        map.put("catagory", rider.getRentType());
        List<Deposit> list = depositRepository.selectAll(map);

        map.put("catagory", 1);
        map.put("orderSql", "t.id desc");
        map.put("riderId", rider.getId());
        map.put("status", 0);
        List<DiscountLog> discountLogs = discountLogRepository.selectAll(map);
        rider.setDepositTypeList(list);
        rider.setDiscountLogList(discountLogs);
        model.addAttribute("rider",rider);
        return "payLog/operate_yj";
    }
    @RequestMapping("/payLog/operate_cz")
    public String gotoOperateCz(Integer id,HttpServletResponse response,
                               HttpServletRequest request, Model model) {
        Rider rider = riderRepository.selectByPrimaryKey(id);
            if (rider.getState() < 1) {
                throw new RuntimeException("您还没有核准激活,请联系商家");
            }

            if (rider.getRentType() == null) {
                throw new RuntimeException("此用户还没有租用类型");
            }
            Map map = new HashMap();
            map.put("departmentId", rider.getDepartmentId());
            map.put("rentTypeId", rider.getRentType());
            map.put("valid", true);
            map.put("orderSql", "t.id desc");
            List<Charge> list = chargeRepository.selectAll(map);
            rider.setPayTypeList(list);

            map.put("riderId", rider.getId());
            map.put("status", 0);
            map.put("catagory", 1);
            List<DiscountLog> discountLogs = discountLogRepository.selectAll(map);
            map.clear();
            map.put("riderId", rider.getId());
            map.put("catagory", "充值");
            int count =payLogRepository.selectCount(map);
            if (count < 1) {
                List<DiscountLog> discountLogs_ = new ArrayList<>();
                discountLogs.forEach(discountLog -> {
                    if (discountLog.getDiscount().getFirstValid()) {
                        discountLogs_.add(discountLog);
                    }
                });
                rider.setDiscountLogList(discountLogs_);
            }else{
                rider.setDiscountLogList(discountLogs);
            }


        model.addAttribute("rider",rider);
        return "payLog/operate_cz";
    }


    public void returnmsg(Integer orderId) throws Exception {

        PayLog order = payLogRepository.selectByPrimaryKey(Integer.valueOf(orderId));
            if (StringUtils.isNotBlank(order.getDiscountIds())) {
                String[] ids = order.getDiscountIds().split(",");
                for (String id : ids) {
                    DiscountLog discountLog = discountLogRepository.selectByPrimaryKey(Integer.valueOf(id));
                    if (discountLog != null) {
                        DiscountLog updataLog = new DiscountLog();
                        updataLog.setId(discountLog.getId());
                        updataLog.setEndDate(new Date().getTime());
                        updataLog.setStatus(1);
                        discountLogRepository.updateByPrimaryKeySelective(updataLog);
                    }
                }
            }
            Rider rider = riderRepository.selectByPrimaryKey(order.getRiderId());
            Rider update = new Rider();
            PayLog updateOrder = new PayLog();
            if ("押金".equals(order.getCatagory())) {
                update.setState(RiderStatus.CANCEL.value);
                rider.setCompanyName(null);
                rider.setCompanyId(null);
                rider.setJhDate(null);
                riderRepository.updateByPrimaryKey(rider);
            } else if ("充值".equals(order.getCatagory())) {
                update.setEndDate(order.getEndDate());
            } else if ("充值其它".equals(order.getCatagory())) {

            }
            updateOrder.setId(order.getId());
            updateOrder.setStatus(1);
            payLogRepository.updateByPrimaryKeySelective(updateOrder);
            update.setId(rider.getId());
            //总金额
            BigDecimal begin = rider.getBalance() == null ? new BigDecimal(0) : rider.getBalance();
            update.setBalance(begin.add(order.getPayMoney()));
            riderRepository.updateByPrimaryKeySelective(update);
    }
    @PostMapping("/payLog/recharge")
    public ResponseEntity<Object> recharge(PayLog payLog) {
        Map map = null;
        try {
            payLog.setCreateDate(new Date().getTime());
            payLog.setStatus(0);
            Rider rider = riderRepository.selectByPrimaryKey(payLog.getRiderId());
            BigDecimal discountMoneys = BigDecimal.ZERO;
            BigDecimal payMoneys = BigDecimal.ZERO;
            if (StringUtils.isNotBlank(payLog.getDiscountIds())) {
                String[] ids = payLog.getDiscountIds().split(",");
                for (String id : ids) {
                    DiscountLog discountLog = discountLogRepository.selectByPrimaryKey(Integer.valueOf(id));
                    if(discountLog==null||!discountLog.getValid()||discountLog.getStatus()==1){
                        log.error("优惠券无效，请重新选择:"+discountLog.getId());
                        return new ResponseEntity<Object>(ErrorCode.defaultInstance("优惠券无效，请重新选择:"+discountLog.getId()), HttpStatus.INTERNAL_SERVER_ERROR);
                    }
                    discountMoneys = discountMoneys.add(discountLog.getDiscountMoney());
                }
            }
            //押金
            if ("押金".equals(payLog.getCatagory())) {
                Deposit deposit = depositRepository.selectByPrimaryKey(payLog.getPackageId());
                if (deposit == null) {
                    log.error("找不到押金对象:"+payLog.getPackageId());
                    return new ResponseEntity<Object>(ErrorCode.defaultInstance("找不到押金对象:"+payLog.getPackageId()), HttpStatus.INTERNAL_SERVER_ERROR);
                }
                payMoneys = new BigDecimal(deposit.getValue());
                payLog.setPackageName(deposit.getName());
                payLog.setMemo(deposit.getCatagory().equals("1")?"单电池租赁":"整车租赁");
            }else if ("充值".equals(payLog.getCatagory())) {
                if (payLog.getPackageId() == -1) {
                    log.error("缴费类型错误，充值错误-1");
                    return new ResponseEntity<Object>(ErrorCode.defaultInstance("缴费类型错误，充值错误-1"), HttpStatus.INTERNAL_SERVER_ERROR);
                }else{
                    Charge charge = chargeRepository.selectByPrimaryKey(payLog.getPackageId());
                    if (charge == null) {
                        log.error("找不到充值对象:"+payLog.getPackageId());
                        return new ResponseEntity<Object>(ErrorCode.defaultInstance("找不到充值对象:"+payLog.getPackageId()), HttpStatus.INTERNAL_SERVER_ERROR);
                    }
                    payMoneys = new BigDecimal(charge.getValue());
                    if (rider.getEndDate() == null||rider.getEndDate()<(new Date().getTime())) {
                        payLog.setBeginDate(new Date().getTime());
                    }else{
                        payLog.setBeginDate(rider.getEndDate()+24*60*60*1000);
                    }
                    payLog.setPackageName(charge.getName());
                    payLog.setEndDate(payLog.getBeginDate()+Long.valueOf(charge.getCode())*30*24*60*60*1000);
                }

            }else if ("充值其它".equals(payLog.getCatagory())) {
                if (payLog.getPackageId() == -1) {
                    payMoneys = payLog.getPayMoney().add(payLog.getDiscountMoney());
                }else{
                    log.error("缴费类型错误，充值其它错误非-1");
                    return new ResponseEntity<Object>(ErrorCode.defaultInstance("缴费类型错误，充值其它错误非-1"), HttpStatus.INTERNAL_SERVER_ERROR);
                }

            }else{
                log.error("缴费类型错误");
                return new ResponseEntity<Object>(ErrorCode.defaultInstance("缴费类型错误"), HttpStatus.INTERNAL_SERVER_ERROR);
            }
            payMoneys = payMoneys.subtract(discountMoneys);
            if (payMoneys.doubleValue() != payLog.getPayMoney().doubleValue()) {
                log.error("前后台金额不符");
                return new ResponseEntity<Object>(ErrorCode.defaultInstance("前后台金额不符"), HttpStatus.INTERNAL_SERVER_ERROR);
            }
            payLog.setPhone(rider.getPhone());
            payLog.setRiderName(rider.getName());
            payLogRepository.insert(payLog);
            this.returnmsg(payLog.getId());
        } catch (Exception e) {
            log.error(e.toString(), e);
            return new ResponseEntity<Object>(ErrorCode.defaultInstance("充值失败"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<Object>(map, HttpStatus.OK);
    }



    @RequestMapping("/payLog/operate")
    public String gotoOperate(Integer id,HttpServletResponse response,
                               HttpServletRequest request, Model model) {
        PayLog payLog = new PayLog();
        if(id!=null){
            payLog = payLogRepository.selectByPrimaryKey(id);
        }
        model.addAttribute("payLog",payLog);
        return "payLog/operate";
    }

    @PostMapping("/payLog/save")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity save(PayLog payLog, HttpServletRequest request,
                              HttpServletResponse response, Model model) {
        try {
            if(payLog.getId()!=null){
                payLogRepository.updateByPrimaryKey(payLog);
            }else {
                Integer a = payLogRepository.insert(payLog);
            }
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }

    @DeleteMapping("/payLog/delete")
    public ResponseEntity setRiderState(Integer id, Integer state) {
        try {
            PayLog payLog = new PayLog();
            payLog.setId(id);
            payLogRepository.updateByPrimaryKeySelective(payLog);
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }
}
